package com.ldg.gateway.config;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 类名：
 * 功能：自定义断言规则
 * AgeRoutePredicateFactory: 命名规则：断言名称+RoutePredicateFactory，如：AgeRoutePredicateFactory，此时的断言名字叫Age
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

	public AgeRoutePredicateFactory() {
		super(Config.class);
	}

	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge","maxAge");
	}

	@Override
	public Predicate<ServerWebExchange> apply(Config config) {
		return exchange -> {
			String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
			if(StringUtils.isNotBlank(ageStr)){
				int age = new Integer(ageStr);
				return age >= config.getMinAge() && age <= config.getMaxAge();
			}
			return false;
		};
	}
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	public static class Config{
		private int minAge;
		private int maxAge;
	}
}
